#include "StdAfx.h"
#include "WndResize.h"


CWndResize::CWndResize(void)
{
	_oldWidth = 0;
	_oldHeight = 0;
	_pHeader = NULL;
}


CWndResize::~CWndResize(void)
{
	_locker.Lock();

	RectInfo* pdel = _pHeader;

	while(pdel != NULL)
	{
		_pHeader = pdel->pnext;
		delete pdel;
		pdel = _pHeader;
	}

	_locker.Unlock();
}

void CWndResize::InitWndSize(float width, float height)
{
	_oldWidth = width;
	_oldHeight = height;
}

void CWndResize::ResetWndSize(float width, float height)
{
	_oldWidth = width;
	_oldHeight = height;
}

RectInfo* CWndResize::AddWnd(CWnd* wnd, CWnd* parent, DWORD flag)
{
	CRect rt;

	wnd->GetWindowRect(&rt);

	if(parent != NULL)
	{
		parent->ScreenToClient(&rt);
	}
	else
	{
		wnd->ScreenToClient(&rt);
	}
	

	RectInfo*	info = new RectInfo();

	memcpy(&(info->rect), &rt, sizeof(CRect));

	info->fleft = (float)rt.left;
	info->ftop = (float)rt.top;
	info->fbottom = (float)rt.bottom;
	info->fright = (float)rt.right;
	info->wnd = wnd;
	info->flag = flag;

	AddRectInfo(info);

	return info;
}

void CWndResize::AddRectInfo(RectInfo* info)
{
	ASSERT(info->pnext == NULL);

	_locker.Lock();
	if (_pHeader == NULL)
	{
		_pHeader = info;
		_locker.Unlock();
		return;
	}

	RectInfo* pfind = _pHeader;

	while(pfind->pnext != NULL)
	{
		pfind = pfind->pnext;
	}

	pfind->pnext = info;

	_locker.Unlock();
}

RectInfo* CWndResize::FindRectInfo(DWORD flag)
{
	_locker.Lock();

	RectInfo* pfind = _pHeader;

	while(pfind != NULL)
	{
		if(pfind->flag == flag)
		{
			break;
		}

		pfind = pfind->pnext;
	}

	_locker.Unlock();

	return pfind;
}

BOOL	CWndResize::Resize(CWnd* wnd, float width, float height, CRect* rect, CWnd* parent, DWORD flag)
{
	ASSERT(flag != 0);

	RectInfo*	info = FindRectInfo(flag);

	if (info == NULL)
	{
		info  = AddWnd(wnd, parent, flag);
	}

	info->fleft = info->fleft * width / _oldWidth;
	info->ftop = info->ftop * height / _oldHeight;
	info->fright = info->fright * width / _oldWidth;
	info->fbottom = info->fbottom * height / _oldHeight;

	rect->left = (int)info->fleft;
	rect->top = (int)info->ftop;
	rect->right = (int)info->fright;
	rect->bottom = (int)info->fbottom;

	memcpy(&(info->rect), rect, sizeof(CRect));

	return TRUE;
}